#include "LightFileStorageManager.h"
#include <stdio.h>

namespace LightPlayer {


	const LightPlayer::FileMapInfo FileMapInfo::EMPTY_FILE(0,NULL);



	LightFileStorageManager::LightFileStorageManager(){
	
	}
	
	LightFileStorageManager::~LightFileStorageManager(){
		FileStorageMapType::iterator it = m_FileStorageMap.begin();
		for( ; it != m_FileStorageMap.end(); ++it ) {
			delete[] it->second.buffer;
		}
		m_FileStorageMap.clear();
	}

	LightFileStorageManager* LightFileStorageManager::getInstance(){
		static LightFileStorageManager* pInstance = NULL;
		if( !pInstance ) {
			pInstance = new LightFileStorageManager();
		}
		return pInstance;
	}

	void LightFileStorageManager::addFileToStorage( const string& key, uint8* file, uint32 length ){
		if( m_FileStorageMap.find( key ) != m_FileStorageMap.end() ){
			printf("warning addFileToStorage : a file was already found at the same key, it will be replaced ! \n" );
			delete[] m_FileStorageMap[key].buffer;
		}
		m_FileStorageMap[key].buffer = file;
		m_FileStorageMap[key].length = length;
	}

	const FileMapInfo& LightFileStorageManager::getFile( const string& key ) const{
		FileStorageMapType::const_iterator it = m_FileStorageMap.find( key );
		if( it != m_FileStorageMap.end() ){
			return it->second;
		}
		return FileMapInfo::EMPTY_FILE;
	}

	const FileMapInfo& LightFileStorageManager::getLoadedSwfFile( const char* fileName )
	{
		string fileKey(fileName);

		if( getFile(fileKey) != FileMapInfo::EMPTY_FILE ){
			// file already loaded, return FileMapinfo
			return getFile(fileKey);
		} else {
			// do the loading of the file

			FILE* f = NULL;
			fopen_s(&f,fileName,"rb");
			if(f){
				// read header
				uint32 header=0;
				uint32 file_length=0;
				fread(&header,sizeof(uint32),1,f);
				fread(&file_length,sizeof(uint32),1,f);

				uint32 m_version = (header >> 24) & 255;
				if ( (header & 0x0FFFFFF) != 0x00535746 ){
					if( (header & 0x0FFFFFF) == 0x00535743 ){
						printf("Error, doesn't support compressed version of swf.\n");
					} else {
						printf("Error, file does not start with a SWF header!\n");
					}
					fclose(f);
					return FileMapInfo::EMPTY_FILE;
				}

				fseek(f, 0L, SEEK_SET);
				uint8* pData = new uint8[file_length];
				uint32 size_read = fread_s(pData,file_length,sizeof(uint8),file_length,f);

				assert( size_read == file_length );
				if( size_read != file_length ){
					printf("Error, A problem occur during the read of the file [%s], the size readed is differente than the swf file format expect!\n", fileName );
					delete[] pData;
					fclose(f);
					return FileMapInfo::EMPTY_FILE;
				}

				addFileToStorage( fileKey, pData, file_length );
				fclose(f);
				return getFile(fileKey);
			} else {
				printf("Error, cannot open file : %s\n",fileName);
			}

			return FileMapInfo::EMPTY_FILE;
		}

		return FileMapInfo::EMPTY_FILE;
	}
};